package com.suneast.suneaststore.modules.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suneast.suneaststore.API;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.bean.common.PictureBean;
import com.suneast.suneaststore.modules.common.event.PicUploadResult;
import com.suneast.suneaststore.util.log.LatteLogger;
import com.suneast.suneaststore.util.net.RestClient;

import org.greenrobot.eventbus.EventBus;

public class PictureHandler {
    /**
     * 上传单张图片， See @link{com.}
     *
     * @param path 图片的路径
     * @param who  谁调用的(class simple name+自定义信息（可为空）)，eventbus将会把此信息封装到event里，关注者需check此参数
     */
    @Deprecated
    public static void upload(String path, String who) {
        RestClient.builder()
                .url(API.PIC_UPLOAD)
                .params("token", AccountManager.getToken())
                .file(path)
                .success((response) -> {
                    LatteLogger.json(API.PIC_UPLOAD, response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new PicUploadResult(Flag.Result.SUCCEED, who,
                                JSON.parseObject(rootJObj.getJSONObject("data").toJSONString(), PictureBean.class)));
                    } else {
                        EventBus.getDefault().post(new PicUploadResult(Flag.Result.FAILURE, who, rootJObj.getString("msg")));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", API.PIC_UPLOAD + " failure: who, " + who);
                    EventBus.getDefault().post(new PicUploadResult(Flag.Result.FAILURE, who, "请求失败"));
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", API.PIC_UPLOAD + " error, code="
                            + code + " msg=" + msg);
                    EventBus.getDefault().post(new PicUploadResult(Flag.Result.FAILURE, who, "code = " + code + " msg = " + msg));
                })
                .build()
                .upload();
    }

    /**
     * 通知后台用户删除了某张图片，其实后台爱删不删
     *
     * @param id 图片的id
     *           结果估计没人感兴趣，暂时不通知了
     */
    @Deprecated
    public static void delete(int id) {
        RestClient.builder()
                .url(API.PIC_DELETE)
                .params("token", AccountManager.getToken())
                .params("id", id)
                .success((response) -> {
                    LatteLogger.json(API.USER_ORDER_LIST, response);
                })
                .failure(() -> LatteLogger.e("error", "requestListByStatus failure"))
                .error((int code, String msg) -> LatteLogger.e("error", "requestListByStatus error code = "
                        + code + " msg = " + msg))
                .build()
                .post();
    }
}
